package com.todo.server.DAO.user;

import org.hibernate.Session;

import com.todo.server.DAO.user.model.UserDAO;
import com.todo.orm.user.User;
import com.todo.util.HibernateUtil;

public class UserDAOImpl implements UserDAO{

	public void addUser(User user) {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.persist(user);
			session.getTransaction().commit();

		} catch (Exception e) {
			System.err.println("Error --->" + e.getMessage());
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		
	}

	public User getUserById(int id) {
		Session session = null;
	    User user = null;
	    try {
	      session = HibernateUtil.getSessionFactory().openSession();
	      user = (User) session.load(User.class, id);
	    } catch (Exception e) {
	    	System.err.println("Error --->" + e.getMessage());
	    } finally {
	      if (session != null && session.isOpen()) {
	        session.close();
	      }
	    }
	    return user;
	}
	
	public User getUserByLogin(String login){
		Session session = null;
	    User user = null;
	    try {
	      session = HibernateUtil.getSessionFactory().openSession();
	      user = (User) session.load(User.class, login);
	    } catch (Exception e) {
	    	System.err.println("Error --->" + e.getMessage());
	    } finally {
	      if (session != null && session.isOpen()) {
	        session.close();
	      }
	    }
	    return user;
	}

}
